package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BusinessException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    //1、检查当前分类下是否有对应的菜品
// SELECT COUNT(*) FROM `dish` WHERE category_id = 1397844263642378242
    //注入category依赖用来调用删除方法
    @Autowired
    CategoryMapper category;
    //注入套餐的mapper用来调用查寻方法
    @Autowired
    SetmealMapper setmeal;
    //注入菜品的mapper用来调用查寻方法
    @Autowired
    DishMapper dish;
//自定义类删除方法因为前端是?id
    public void shanchu( Long id) {
        //创建对象参数是菜品用来看这个id有没有在菜品表里
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        //+where条件看id是否一致
        qw.eq(Dish::getCategoryId, id);
        //SELECT COUNT(*) FROM `dish` WHERE category_id = id
        Integer count = dish.selectCount(qw);
        //如果有数说明在菜品表里
        if (count > 0) {
            //抛出异常
            throw new BusinessException("该分类下有菜品，不能删除");
        }
        //第二个查询这个id有没有在套餐表里
        LambdaQueryWrapper<Setmeal> qw2 = new LambdaQueryWrapper<>();
        //id是否一致
        qw2.eq(Setmeal::getCategoryId, id);
        //SELECT COUNT(*) FROM `setmeal` WHERE category_id= 1397844263642378242
        Integer count1 = setmeal.selectCount(qw2);
        if (count1 > 0) {
            throw new BusinessException("该分类下有套餐，不能删除");
        }
        //id在菜品表和套餐表里都没有调用根据这个id删除方法
        category.deleteById(id);
    }


    @Override
    public List<Category> selectBytype(Integer type) {
        QueryWrapper<Category> qw=new QueryWrapper<>();
        qw.lambda().eq(type!=null,Category::getType,type);
        qw.lambda().orderByDesc(type!=null,Category::getSort);
        List<Category> categories = category.selectList(qw);
        return categories;
    }
}
